package cn.edu.sdjzu.xg.bysj.dao;

import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisor;
import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisorEntry;
import util.JdbcHelper;

import java.sql.*;

public class ApplicationForSupervisorDao {
    private static ApplicationForSupervisorDao applicationForSupervisorDao =
            new ApplicationForSupervisorDao();


    private ApplicationForSupervisorDao() {
    }

    public static ApplicationForSupervisorDao getInstance() {
        return applicationForSupervisorDao;
    }

    public static boolean add(ApplicationForSupervisor applicationForSupervisor, Connection connection)
            throws SQLException {
        //创建sql语句
        String addApplicationForSupervisor_sql =
                "insert into ApplicationForSupervisor (selfIntroduction,year,student_id) values " +
                        "(?,?,?)";
        String addApplicationForSupervisorEntry_sql =
                "insert into ApplicationForSupervisorEntry (priority,teacher_id,applicationForSupervisor_id) values " +
                        "(?,?,?);";
        //在该链接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(addApplicationForSupervisor_sql, Statement.RETURN_GENERATED_KEYS);
        PreparedStatement pstmt2 = connection.prepareStatement(addApplicationForSupervisorEntry_sql);
        //为添加ApplicationForSupervisor表的预编译语句赋值
        pstmt.setString(1, applicationForSupervisor.getSelfIntroduction());
        pstmt.setInt(2, applicationForSupervisor.getYear());
        pstmt.setInt(3, applicationForSupervisor.getStudent().getId());
        int idOfAddedApplicationForSupervisor = 0;
        int affectedRowNum = pstmt.executeUpdate();
        //获取新增对象id并为applicationForSupervisor赋值
        ResultSet resultSet = pstmt.getGeneratedKeys();
        if (resultSet.next()) {
            //读取第一个
            idOfAddedApplicationForSupervisor = resultSet.getInt(1);
            applicationForSupervisor.setId(idOfAddedApplicationForSupervisor);
        }
        JdbcHelper.close(resultSet, null);
        for (ApplicationForSupervisorEntry c : applicationForSupervisor.getApplicationForSupervisorEntries()) {
            pstmt2.setInt(1, c.getPriority());
            pstmt2.setInt(2, c.getTeacher().getId());
            pstmt2.setInt(3, idOfAddedApplicationForSupervisor);
            int affectedRowNum2 = pstmt2.executeUpdate();

        }
        JdbcHelper.close(pstmt2, null);
        JdbcHelper.close(pstmt, null);
        if (affectedRowNum == 0) {
            return false;
        }
        return true;
    }
}
